'use client'

import React, { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import {
    Card,
    Button,
    Typography,
    Space,
    Tag,
    Breadcrumb,
    Spin,
    Alert,
    Row,
    Col
} from 'antd'
import {
    ArrowLeftOutlined,
    ExperimentOutlined,
    EyeOutlined,
    ScissorOutlined,
    SearchOutlined,
    HomeOutlined,
    DatabaseOutlined
} from '@ant-design/icons'
import { useImageStore } from '@/stores/imageStore'
import { useUIStore } from '@/stores/uiStore'
import { mockDatasets } from '@/utils/mockData'

const { Title, Text, Paragraph } = Typography

interface TaskSelectorProps {
    datasetId: string
}

// 任务类型图标映射
const taskTypeIcons = {
    detection: <SearchOutlined />,
    classification: <EyeOutlined />,
    segmentation: <ScissorOutlined />
}

// 任务类型颜色映射
const taskTypeColors = {
    detection: 'blue',
    classification: 'green',
    segmentation: 'orange'
}

// 任务类型中文名称
const taskTypeNames = {
    detection: '病灶检测',
    classification: '影像分类',
    segmentation: '图像分割'
}

export const TaskSelector: React.FC<TaskSelectorProps> = ({ datasetId }) => {
    const router = useRouter()
    const { loadDataset, currentDataset, loadingStates, errors } = useImageStore()
    const { setSelectedTask, updateBreadcrumbs } = useUIStore()
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const loadDatasetData = async () => {
            setLoading(true)
            try {
                // 在实际应用中，这里会调用 loadDataset(datasetId)
                // 现在使用模拟数据
                const dataset = mockDatasets.find(d => d.id === datasetId)
                if (dataset) {
                    // 模拟加载延迟
                    await new Promise(resolve => setTimeout(resolve, 500))
                }
            } catch (error) {
                console.error('Failed to load dataset:', error)
            } finally {
                setLoading(false)
            }
        }

        loadDatasetData()

        // 更新面包屑
        updateBreadcrumbs([
            { label: '首页', path: '/', isActive: false },
            { label: '数据集', path: `/dataset/${datasetId}`, isActive: true }
        ])
    }, [datasetId, loadDataset, updateBreadcrumbs])

    const handleTaskSelect = (taskId: string) => {
        setSelectedTask(taskId)
        router.push(`/task/${datasetId}/${taskId}`)
    }

    const handleBackToHome = () => {
        router.push('/')
    }

    // 获取当前数据集（使用模拟数据）
    const dataset = mockDatasets.find(d => d.id === datasetId)

    if (loading) {
        return (
            <div className="task-selector h-screen flex items-center justify-center">
                <div className="text-center">
                    <Spin size="large" />
                    <div className="mt-4">
                        <Text>正在加载数据集信息...</Text>
                    </div>
                </div>
            </div>
        )
    }

    if (!dataset) {
        return (
            <div className="task-selector h-screen flex items-center justify-center">
                <Alert
                    message="数据集未找到"
                    description={`无法找到ID为 ${datasetId} 的数据集`}
                    type="error"
                    showIcon
                    action={
                        <Button type="primary" onClick={handleBackToHome}>
                            返回首页
                        </Button>
                    }
                />
            </div>
        )
    }

    return (
        <div className="task-selector min-h-screen bg-gray-50">
            {/* 头部导航 */}
            <div className="header bg-white shadow-sm border-b">
                <div className="max-w-7xl mx-auto px-4 py-4">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-4">
                            <Button
                                type="text"
                                icon={<ArrowLeftOutlined />}
                                onClick={handleBackToHome}
                            >
                                返回首页
                            </Button>
                            <Breadcrumb
                                items={[
                                    {
                                        href: '/',
                                        title: (
                                            <>
                                                <HomeOutlined />
                                                <span>首页</span>
                                            </>
                                        )
                                    },
                                    {
                                        title: (
                                            <>
                                                <DatabaseOutlined />
                                                <span>数据集</span>
                                            </>
                                        )
                                    },
                                    {
                                        title: dataset.name
                                    }
                                ]}
                            />
                        </div>
                    </div>
                </div>
            </div>

            {/* 主要内容 */}
            <div className="main-content max-w-7xl mx-auto px-4 py-8">
                {/* 数据集信息 */}
                <Card className="mb-8">
                    <div className="flex items-start space-x-6">
                        <div className="flex-shrink-0">
                            <div className="w-16 h-16 bg-blue-100 rounded-lg flex items-center justify-center">
                                <DatabaseOutlined className="text-2xl text-blue-600" />
                            </div>
                        </div>
                        <div className="flex-1">
                            <Title level={2} className="mb-2">{dataset.name}</Title>
                            <Paragraph className="text-gray-600 mb-4">
                                {dataset.description}
                            </Paragraph>
                            <Space wrap>
                                <Tag color="blue">{dataset.type}</Tag>
                                <Tag>{dataset.imageCount} 张影像</Tag>
                                <Tag>{(dataset.size / (1024 * 1024)).toFixed(1)} MB</Tag>
                                {dataset.tags?.map(tag => (
                                    <Tag key={tag} color="default">{tag}</Tag>
                                ))}
                            </Space>
                        </div>
                    </div>
                </Card>

                {/* 任务选择 */}
                <div className="mb-6">
                    <Title level={3} className="mb-4">
                        <ExperimentOutlined className="mr-2" />
                        选择分析任务
                    </Title>
                    <Text type="secondary" className="text-base">
                        请选择要执行的医学影像分析任务
                    </Text>
                </div>

                <Row gutter={[24, 24]}>
                    {dataset.tasks.map((task) => (
                        <Col xs={24} sm={12} lg={8} key={task.id}>
                            <Card
                                hoverable
                                className="task-card h-full"
                                actions={[
                                    <Button
                                        key="select"
                                        type="primary"
                                        onClick={() => handleTaskSelect(task.id)}
                                        block
                                    >
                                        选择任务
                                    </Button>
                                ]}
                            >
                                <div className="text-center mb-4">
                                    <div className="inline-flex items-center justify-center w-12 h-12 bg-blue-100 rounded-lg mb-3">
                                        <span className="text-xl text-blue-600">
                                            {taskTypeIcons[task.type as keyof typeof taskTypeIcons]}
                                        </span>
                                    </div>
                                    <Title level={4} className="mb-2">{task.name}</Title>
                                    <Tag
                                        color={taskTypeColors[task.type as keyof typeof taskTypeColors]}
                                        className="mb-3"
                                    >
                                        {taskTypeNames[task.type as keyof typeof taskTypeNames]}
                                    </Tag>
                                </div>

                                <Paragraph
                                    className="text-gray-600 text-center"
                                    ellipsis={{ rows: 3 }}
                                >
                                    {task.description}
                                </Paragraph>

                                <div className="mt-4 pt-4 border-t">
                                    <div className="flex items-center justify-between text-sm text-gray-500">
                                        <span>状态</span>
                                        <Tag
                                            color={task.status === 'idle' ? 'default' :
                                                task.status === 'running' ? 'processing' :
                                                    task.status === 'completed' ? 'success' : 'error'}
                                        >
                                            {task.status === 'idle' ? '就绪' :
                                                task.status === 'running' ? '运行中' :
                                                    task.status === 'completed' ? '已完成' : '错误'}
                                        </Tag>
                                    </div>
                                </div>
                            </Card>
                        </Col>
                    ))}
                </Row>

                {/* 如果没有可用任务 */}
                {dataset.tasks.length === 0 && (
                    <Card className="text-center py-12">
                        <ExperimentOutlined className="text-4xl text-gray-400 mb-4" />
                        <Title level={4} className="text-gray-600 mb-2">
                            暂无可用任务
                        </Title>
                        <Text type="secondary">
                            该数据集当前没有配置任何分析任务
                        </Text>
                    </Card>
                )}
            </div>
        </div>
    )
}

export default TaskSelector